﻿#include <iostream>

static void setValue(int* matrix, int colSize, int x, int y, int value)
{
	matrix[x + y * colSize] = value;
}

static int getValue(int* matrix, int colSize, int x, int y)
{
	return matrix[x + y * colSize];
}

static void printMatrix(int* matrix, int colSize)
{
	for (int y = 0; y < colSize; y++)
	{
		for (int x = 0; x < colSize; x++)
		{
			printf("%d,", *(matrix + x + y * colSize));
		}

		printf("\n");
	}

	printf("===============\n");
}

// 旋转外围的一圈
static void rotateOneCircle(int* matrix, int colSize, int startX, int startY, int n)
{
	for (int i = 0; i < n - 1; i++)
	{
		int tmp = getValue(matrix, colSize, startX, startY + n - 1 - i);

		setValue(matrix, colSize, startX, startY + n - 1 - i, getValue(matrix, colSize, startX + n - 1 - i, startY + n - 1));

		setValue(matrix, colSize, startX + n - 1 - i, startY + n - 1, getValue(matrix, colSize, startX + n - 1, startY + i));

		setValue(matrix, colSize, startX + n - 1, startY + i, getValue(matrix, colSize, startX + i, startY));

		setValue(matrix, colSize, startX + i, startY, tmp);
	}
}

static void rotate(int* matrix, int colSize)
{
	int startX = 0;
	int startY = 0;
	int endX = startX + colSize - 1;
	int endY = startY + colSize - 1;
	int n = 0;
	while (startX <= endX && startY <= endY)
	{
		rotateOneCircle(matrix, colSize, startX, startY, colSize - n);
		++startX;
		++startY;
		--endX;
		--endY;
		n += 2;
	}
}

/**
 * 给定一个正方形矩阵，只用有限几个变量，实现矩阵中每个位置的顺时针转动90°，比如如下的矩阵
 *  0   1   2   3
 *  4   5   6   7
 *  8   9  10  11
 * 12  13  14  15
 * 矩阵应该被调整为:
 *  12   8   4   0
 *  13   9   5   1
 *  14  10   6   2
 *  15  11   7   3
 *
 *  思路：
 *  先看最外围的一圈
 *
 *  0   1   2   3
 *  4           7
 *  8          11
 * 12  13  14  15
 *
 * 可以将这一圈数字分为3组，
 * (1)0,3,15,12
 * (2)1,7,14,8
 * (3)2,11,13,4
 *
 * 调整后，每组的数字依次占据后一个的位置:
 * (1)12,0,3,15
 * (2)8,1,7,14
 * (3)4,2,11,13
 *
 * 即:
 *
 *   12  8  4  0
 *   13        1
 *   14        2
 *   15 11  7  3
 *
 * 推广到N*N的矩阵，则将外围一圈数字分为N-1组进行类似的操作.
 *
 */
int main_Clockwise()
{
	//int matrix[][4] = {
	//	{0,1,2,3,},
	//	{4,5,6,7,},
	//	{8,9,10,11,},
	//	{12,13,14,15,},
	//};

	int matrix[][6] = {
		{0,1,2,3,4,5,},
		{6,7,8,9,10,11,},
		{12,13,14,15,16,17,},
		{18,19,20,21,22,23,},
		{24,25,26,27,28,29,},
		{30,31,32,33,34,35,},
	};

	int rowSize = sizeof(matrix) / sizeof(matrix[0]);
	int colSize = sizeof(matrix[0]) / sizeof(int);

	rotate(matrix[0], colSize);
	printMatrix(matrix[0], colSize);
	return 0;
}